<?php
require_once '../setting/system.php';
if(1 && $lang = _language()) {
	@ini_set('session.save_path', '../var/tmp/www');
	@ini_set('error_log', '../var/log/' . $lang['host'] . '.log');
	if(!empty($lang['config'])) {
		foreach($lang['config'] AS $key => $cfg) {
			$icfg = isset($config[$key]) ? $config[$key] : array();
			if(is_array($cfg)) {
				$config[$key] = array_merge($icfg, $cfg);
			} else {
				$config[$key] = $cfg;
			}
		}
	}
	define('_STATIC_HTTP', (isset($config['http']['static']) ? $config['http']['static'] : ''));
	$config['language'] = $lang['key'];
	if(preg_match('/([a-z0-9-]+\.[a-z]{2,10})$/is', strtolower($_SERVER['HTTP_HOST']), $host)) {
		$config['session']['cookie_domain'] = '.' . $host[1];
	}
}
$request = $_SERVER['REQUEST_URI'];
if(_isRobot() && !preg_match('/favicon\.ico/i', $request) && !preg_match('/(\/sns|@|\/t\/)/i', $request)) {
	$config['session']['db_handler'] = false;
	$dir = isset($config['language']) ? $config['language'] : '';
	define('_ROBOT_FILE', '../var/robots' . _filename($dir));
	// 蜘蛛爬虫缓存 3 天
	if(file_exists(_ROBOT_FILE) && time() < intval(@filemtime(_ROBOT_FILE)) + 259200) {
		$error = null;
		try {
			echo @file_get_contents(_ROBOT_FILE);
		} catch (Exception $e) {
			$error = $e;
		}
		if($error === null) exit;
	}
}
if(isset($_REQUEST['ns']) || preg_match('/favicon\.ico$/i', $request) || preg_match('/robots\.txt$/i', $request)) {
	$config['session']['db_handler'] = false;
}
require_once '../app/web.php';

function _filename($dir) {
	$client = 'web';
	if(isset($_SERVER['HTTP_VIA']) && stristr(strtolower($_SERVER['HTTP_VIA']), "wap")) {
		$client = 'wap';
	}
	$re = "/(nokia|sony|ericsson|mot|samsung|sgh|lg|philips|panasonic|alcatel|lenovo|cldc|midp|mmp|wap|ppc|phone|symbian|mobile|brew|iphone|android)/i";
	if(isset($_SERVER['HTTP_USER_AGENT']) && preg_match($re, $_SERVER['HTTP_USER_AGENT'], $_ua)) {
		$client = strtolower($_ua[1]);
	}
	if(isset($_SERVER['HTTP_ACCEPT']) && preg_match('/vnd\.wap\.wml/i', $_SERVER['HTTP_ACCEPT'])) {
		$client = 'wap';
	}
		
	$uri = '/' . trim($_SERVER['REQUEST_URI'], '/');
	if(1 && $pos = strpos($uri, '?')) {
		$uri = substr($uri, 0, $pos);
	}
	$code = md5($uri);
	$a = substr($code, 1, 1);
	$b = substr($code, -2, 2);
	$c = substr($code, 8, 16);
	return "/$dir-$client/$a/$b/$c.html";
}

function _isRobot() {
	$_client = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'unknown';
	return preg_match('/(Bot|Crawl|Spider|lycos|robozilla|slurp|sohu\-search|unknown)/isU', $_client);
}

function _language() {
	$host = $_SERVER['HTTP_HOST'];
	$http = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
	$http .= $host;
	$http .= $_SERVER['SERVER_PORT'] == 80 ? '' : ':' . $_SERVER['SERVER_PORT'];
	$http .= $_SERVER['PHP_SELF'];
	$http = dirname($http);

	$lang = (array) include '../setting/language.php';
	foreach($lang AS $key => $v) {
		if(isset($v['enable']) && $v['enable'] == false) {
			unset($lang[$key]);
		}
	}
	$existing = $current = false;
	foreach($lang AS $key => $v) {
		if($v['http'] == $http || (isset($v['domains']) && in_array($host, $v['domains']))) {
			$existing = $key;
			$current = true;
			break;
		}
	}
	if(!$existing) {
		foreach($lang AS $key => $v) {
			$pu = parse_url($v['http']);
			if(strtolower($pu['host']) == 'www.' . $host) {
				$existing = $key;
				break;
			}
		}
	}
	if(!$existing) {
		preg_match('/([a-z0-9-]+\.[a-z]{2,10})$/is', $host, $host1);
		$host1 = strtolower($host1[1]);
		$hosts = array();
		foreach($lang AS $key => $v) {
			$pu = parse_url($v['http']);
			if(preg_match("#$host1$#i", strtolower($pu['host']))) {
				$hosts[] = $key;
			}
		}
		if(!empty($hosts)) {
			$existing = $hosts[rand(0, count($hosts) - 1)];
		}
	}
	if(!$existing) {
		$rand = rand(0, count($lang) - 1);
		$i = 0;
		foreach($lang AS $key => $v) {
			if($rand == $i) {
				$existing = $key;
				break;
			}
			$i++;
		}
	}
	if(!$existing || !isset($lang[$existing])) {
		return null;
	}
	$return = $lang[$existing];
	if(!$current) {
		$url = parse_url($return['http']);
		$http = $url['scheme'] . '://' . $url['host'];
		if(isset($url['port'])) $http .= ':' . $url['port']; 
		$uri = urldecode($_SERVER['REQUEST_URI']);
		$uri = $http . preg_replace('/\/index\.php\//is', "/", $uri);
		header("Location: $uri");
		exit;
	}
	
	$return['key'] = $existing;
	$return['host'] = $host;
	return $return;
}

